package service

import (
	"git.oschina.net/fanbuchi/xgggh/oauth2/model"
	smsCli "git.oschina.net/fanbuchi/xgggh/sms/cli"
	account "git.oschina.net/fanbuchi/xgggh/oauth2/proto/account"
	"git.oschina.net/fanbuchi/xgggh/errs"
	"git.oschina.net/fanbuchi/xgggh/oauth2/utils"
	"git.oschina.net/fanbuchi/xgggh/sms/proto/sms"
)

func Password(userName,password string) (*model.Account,error)  {
	// Fetch the user
	var   result *model.Account
	if len(password)==4 {
		//验证验证码
		req:=com_xgggh_srv_sms.ValidateReq{Mobile:userName,Code:password}
		_,err:=smsCli.Validate(&req)

		if err !=nil{
			return nil,err
		}
		//输入验证码的登陆才创建账户
		reqCreateAccount:=account.CreateReq{UserName:userName,Password:password}
		rsp,err:=AccountCreate(nil,&reqCreateAccount)

		if err!=errs.AccountIsExist && err != nil {
			return nil, err
		}
		result=rsp
		return result,nil
	}
	result,err:=AccountSearchByUserName(userName)

	if err!=nil {
		return nil, err
	}
	//验证密码
	// Check that the password is set
	if len(result.Password)<=0 {
		return nil, errs.UserPasswordNotSet
	}
	// Verify the password
	if utils.VerifyPassword(result.Password, password) != nil {
		return nil, errs.InvalidUsernameOrPassword
	}
	return result,nil
}
